package com.zzuli.dcxt.controller;

import com.zzuli.dcxt.dao.CustomerMapper;
import com.zzuli.dcxt.entiy.Customer;
import com.zzuli.dcxt.entiy.Dishes;
import com.zzuli.dcxt.service.CustomerService;
import com.zzuli.dcxt.utils.PageCommon;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class CustomerController {
    @Autowired
    private CustomerService customerService;

    @Autowired
    private CustomerMapper customerMapper;

    @RequestMapping("/customerlist")
    public String customerlist(Model model){
        List list = customerService.getCustomerList();
        model.addAttribute("list",list);
        return "customer";
    }

    @RequestMapping("/delcustomer")
    public String customerlist(int id){
        customerService.deleteCustomer(id);
        return "redirect:/customerlist.do";
    }

    @RequestMapping("/updatecustomer")
    public String updatecustomer(Customer customer){
        System.out.println(customer);
        customerMapper.updateCustomer(customer);
        return "redirect:/customerlist.do";
    }

    @RequestMapping("/selectOneCustomer")
    public String selectOneCustomer(int id, HttpSession session){
        Customer customer = customerMapper.selectByPrimaryKey(id);
        session.setAttribute("updateCustomer",customer);
        return "updatecustomer";
    }

    /**
     * 分页查询
     *
     * @param pageIndex 当前页
     * @return
     */
    @RequestMapping("/pageUserPage")
    public ModelAndView getUsersByPage(int pageIndex) {
        ModelAndView mv = new ModelAndView();

        //根据总条数和每页条数，得到总页数
        int customerCount = customerMapper.getUserCount();
        int totalPages = PageCommon.getTotalPages(customerCount, PageCommon.PAGE_SIZE);

        if (pageIndex == 0) {
            pageIndex = 1;
        }

        if (pageIndex > totalPages) {
            pageIndex = totalPages;
        }

        Map<String, Integer> cond = new HashMap<>();
        cond.put("start", PageCommon.PAGE_SIZE * (pageIndex - 1));
        cond.put("length", PageCommon.PAGE_SIZE);

        List<Customer> list = customerMapper.getCustomerByPage(cond);

        //分别将当前页，用户列表，总页数存在request域当中，便于页面取值
        mv.addObject("pageIndex", pageIndex);
        mv.addObject("list", list);
        mv.addObject("totalPages", totalPages);

        mv.setViewName("customer");
        return mv;

    }

}
